﻿using Model.DocumentDB;
using Studio.DocumentDB.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Studio.DocumentDB
{
    /// <summary>Query editor.</summary>
    public partial class QueryEditorUserControl : UserControl
    {
        /// <summary>Constructor.</summary>
        public QueryEditorUserControl()
        {
            InitializeComponent();
        }

        private void UserControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (object.Equals(e.NewValue, Visibility.Visible) && !(DataContext is CollectionViewModel))
            {
                throw new InvalidOperationException("Requires a collection as DataContext");
            }
        }

        private async void Execute_Click(object sender, RoutedEventArgs e)
        {
            await ExecuteQueryAsync();
        }

        private async void UserControl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.F5)
            {
                await ExecuteQueryAsync();
            }
        }

        private async Task ExecuteQueryAsync()
        {
            await ErrorHelper.HandleAsync(() =>
            {
                var collection = DataContext as CollectionViewModel;
                var task = collection.QueryResults.RefreshAsync();

                return task;
            }, this, "Query error:  {0}");

            TelemetryAgent.Instance.UseFeature(Features.QueryDocument);
        }
    }
}